<script setup>
import {ipc, Process} from "@/utils/ipcRenderer"
import {ipcApiRoute} from "@/api/main"
import Title from './child/Title.vue'
import Changelog from "@/views/conf/child/Log.vue"
import {useGlobalConf} from '@/utils/useGlobalConf'
import {useLocale} from '@/utils/useLocale'
const $message = useMessage()
const {globalConf, setGlobalConf} = useGlobalConf()
const $confI18n = useLocale('conf')
//关闭窗口
const handleClose = () => {
  ipc.invoke(ipcApiRoute['window.close']).then(({state, message}) => {
    if (!state) {
      ipc.send(ipcApiRoute['nativeBox.showBox'], {
        type: 'error',
        title: 'System Error',
        detail: message
      })
    }
  })
}
//动态渲染菜单标题
const titleVNode_Appear = () => h(Title, {name: $confI18n.value.appearance, size: 20, icon: 'coat'})
const titleVNode_General = () => h(Title, {name: $confI18n.value.common, size: 20, icon: 'general'})
const titleVNode_About = () => h(Title, {name: $confI18n.value.about, size: 20, icon: 'about'})
//更新配置表
const saveConfigToDb = (flag) => {
  ipc.sendSync(ipcApiRoute['home.saveAndSync'], flag)
}
//背景设置
const changeAppTheme = (themeStr) => {
  const mapBgr = {
    white: '#f4f4f8',
    dark: '#2c2c32'
  }
  saveConfigToDb({
    appTheme: themeStr,
    appBackgroundColor: mapBgr[themeStr]
  })
  ipc.sendSync(ipcApiRoute['window.setAllBackgroundColor'], mapBgr[themeStr])
  setGlobalConf({
    appTheme: themeStr
  })
}
//主题设置
const changePrimaryColors = (hexColor) => {
  const mapSuppl = {
    '#18a058': {
      appPrimaryHoverColor: '#36ad6a',
      appPrimaryPressedColor: '#0c7a43',
      appPrimarySupplColor: '#2cb682',
      appMinorPrimaryColor: '#9373ee'
    },
    '#9373ee': {
      appPrimaryHoverColor: '#bba0fa',
      appPrimaryPressedColor: '#7056c7',
      appPrimarySupplColor: '#a98ff1',
      appMinorPrimaryColor: '#5f80e9'
    },
    '#5f80e9': {
      appPrimaryHoverColor: '#8ca8f5',
      appPrimaryPressedColor: '#465fc2',
      appPrimarySupplColor: '#7f99ed',
      appMinorPrimaryColor: '#587df1'
    },
    '#587df1': {
      appPrimaryHoverColor: '#87a9ff',
      appPrimaryPressedColor: '#415fcc',
      appPrimarySupplColor: '#7997f4',
      appMinorPrimaryColor: '#9a7d56'
    },
    '#9a7d56': {
      appPrimaryHoverColor: '#a69377',
      appPrimaryPressedColor: '#73593b',
      appPrimarySupplColor: '#ae9778',
      appMinorPrimaryColor: '#00c3ee'
    },
    '#00c3ee': {
      appPrimaryHoverColor: '#28dafa',
      appPrimaryPressedColor: '#009cc7',
      appPrimarySupplColor: '#33cff1',
      appMinorPrimaryColor: '#039e74'
    },
    '#039e74': {
      appPrimaryHoverColor: '#1fab81',
      appPrimaryPressedColor: '#00785c',
      appPrimarySupplColor: '#35b190',
      appMinorPrimaryColor: '#fa8c16'
    },
    '#fa8c16': {
      appPrimaryHoverColor: '#ffa940',
      appPrimaryPressedColor: '#d46b08',
      appPrimarySupplColor: '#fba345',
      appMinorPrimaryColor: '#e86ca4'
    },
    '#e86ca4': {
      appPrimaryHoverColor: '#f59ac0',
      appPrimaryPressedColor: '#c25188',
      appPrimarySupplColor: '#ed89b6',
      appMinorPrimaryColor: '#fd6874'
    },
    '#fd6874': {
      appPrimaryHoverColor: '#f59ac0',
      appPrimaryPressedColor: '#c25188',
      appPrimarySupplColor: '#ed89b6',
      appMinorPrimaryColor: '#8e8374'
    },
    '#8e8374': {
      appPrimaryHoverColor: '#9c9892',
      appPrimaryPressedColor: '#695e51',
      appPrimarySupplColor: '#a59c90',
      appMinorPrimaryColor: '#18a058'
    }
  }
  saveConfigToDb({
    appPrimaryColor: hexColor,
    ...mapSuppl[hexColor]
  })
  setGlobalConf({
    appPrimaryColor: hexColor
  })
}
//字体大小设置
let debounceTimer
const changeZoom = (zoomFactor) => {
  clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => {//去除抖动
    ipc.send(ipcApiRoute['window.setZoomFactor'], zoomFactor)
  }, 150)
}
//开机设置
const changePowerSetting = (checked) => {
  saveConfigToDb({
    loginPowerOn: checked
  })
  setGlobalConf({
    loginPowerOn: checked
  })
}
//关闭应用设置
const changeCloseWinSetting = (e) => {
  let checkedVal = e.target.value
  saveConfigToDb({
    appCloseWindow: checkedVal
  })
  setGlobalConf({
    appCloseWindow: checkedVal
  })
}
//语言设置
const changeLanguageSetting = (e) => {
  let checkedVal = e.target.value
  saveConfigToDb({
    appLanguageI18n: checkedVal
  })
  setGlobalConf({
    appLanguageI18n: checkedVal
  })
}
//软件更新设置
const changeUpdaterSetting = (e) => {
  let checkedVal = e.target.value
  saveConfigToDb({
    appAutoUpdates: checkedVal
  })
  setGlobalConf({
    appAutoUpdates: checkedVal
  })
}
//检查更新
const fetchAvailableUpdateLoading = ref(false)
const checkForUpdate = () => {
  fetchAvailableUpdateLoading.value = true
  ipc.invoke(ipcApiRoute['home.checkForUpdate'], {
    senderName: 'conf'
  }).then(result => {
    fetchAvailableUpdateLoading.value = false
  }).catch(error => {
    fetchAvailableUpdateLoading.value = false
    //todo 记录日志
  })
}
//修改下载目录
const messageTips = (result) => {
  return new Promise((resolve, reject) => {
    switch (result) {
      case 'NoDir':
        $message.error(computed(() => $confI18n.value.noDir))
        reject(result)
        break
      case 'NoExist':
        $message.error(computed(() => $confI18n.value.dirNoExist))
        reject(result)
        break
      case 'Success':
        resolve()
        break
      default:
        reject(result)
    }
  })
}
const changeDownloadPath = () => {
  ipc.invoke(ipcApiRoute['nativeBox.selectDir'], {
    title: $confI18n.value.selectDir
  }).then((ret) => {
    if (ret.canceled || ret.filePaths.length <= 0) {
      //取消选择
      return
    }

    let dp = ret.filePaths[0]

    ipc.invoke(ipcApiRoute['fs.checkIsDir'], {//目录检查
      path: dp
    }).then(ret => {
      messageTips(ret).then(() => {//保存新目录
        saveConfigToDb({
          appDownloadsPath: dp
        })
        setGlobalConf({
          appDownloadsPath: dp
        })
      })
    })
  }).catch(error => {
    console.error(error)
    $message.error(error.message || 'An error occurred')
  })
}
//查看更新日志
const AppProductName = Process.env.EE_APP_NAME
const AppProductVersion = Process.env.EE_APP_VERSION
const changeLogShow = ref(false)
const changeLogContent = ref('')
const getChangelog = () => {
  ipc.invoke(ipcApiRoute['home.appChangeLog']).then(ret => {
    changeLogShow.value = true
    changeLogContent.value = ret
  })
}
</script>

<template>
  <div class="conf">
    <n-card class="conf--card"
            header-class="conf--card-header"
            content-class="conf--card-content"
            :bordered="false" size="medium"
            style="--n-padding-top:9px;--n-padding-bottom:10px;"
    >
      <!--头部-->
      <template #header>
        <div class="conf--titlebar">
          <span class="conf--titlebar_text" v-text="$confI18n.barTitle"></span>
        </div>
      </template>
      <template #header-extra>
        <n-icon class="conf--close" size="15" @click="handleClose">
          <icon-ep-close/>
        </n-icon>
      </template>
      <!--内容-->
      <template #default>
        <div class="conf--aside">
          <!--侧边菜单-->
          <n-card :bordered="false" class="conf--aside__tree" content-class="conf--aside__menu">
            <n-scrollbar trigger="hover" :x-scrollable="true">
              <n-anchor type="block" :show-rail="false" :show-background="true" :ignore-gap="true"
                        offset-target="#confScrollArea>div" style="--n-link-font-size:15px;">
                <n-anchor-link :title="titleVNode_Appear()" href="#AnchorAppearance" @click.prevent></n-anchor-link>
                <n-anchor-link :title="titleVNode_General()" href="#AnchorGeneral" @click.prevent></n-anchor-link>
                <n-anchor-link :title="titleVNode_About()" href="#AnchorAbout" @click.prevent></n-anchor-link>
              </n-anchor>
            </n-scrollbar>
          </n-card>
          <n-card :bordered="false" class="conf--aside__content" content-class="conf--aside__container">
            <n-scrollbar trigger="hover" :x-scrollable="true" id="confScrollArea">

              <!--外观-->
              <n-card class="conf--aside__thing" :bordered="false" :title="$confI18n.appearance" id="AnchorAppearance">
                <!--背景-->
                <n-thing content-class="thing-content">
                  <template #header>
                    <span class="thing-title" v-text="$confI18n.background"></span>
                  </template>
                  <template #default>
                    <div class="bg-options">
                      <img @click="changeAppTheme('dark')"
                           :class=" ['item', { active: globalConf.appTheme === 'dark' }] "
                           src="@/assets/icons-svg/theme_dark.svg" alt="黑色背景">
                      <img @click="changeAppTheme('white')"
                           :class=" ['item', { active: globalConf.appTheme === 'white' }] "
                           src="@/assets/icons-svg/theme_white.svg" alt="白色背景">
                    </div>
                  </template>
                </n-thing>

                <!--主色-->
                <n-thing content-class="thing-content">
                  <template #header>
                    <span class="thing-title">{{ $confI18n.primaryColor }}</span>
                  </template>
                  <template #default>
                    <n-space>
                      <n-icon @click="changePrimaryColors('#18a058')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#18a058' } ]"
                              color="#18a058" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#9373ee')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#9373ee' } ]"
                              color="#9373ee" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#5f80e9')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#5f80e9' } ]"
                              color="#5f80e9" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#587df1')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#587df1' } ]"
                              color="#587df1" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#9a7d56')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#9a7d56' } ]"
                              color="#9a7d56" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#00c3ee')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#00c3ee' } ]"
                              color="#00c3ee" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#039e74')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#039e74' } ]"
                              color="#039e74" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#fa8c16')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#fa8c16' } ]"
                              color="#fa8c16" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#e86ca4')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#e86ca4' } ]"
                              color="#e86ca4" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#fd6874')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#fd6874' } ]"
                              color="#fd6874" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                      <n-icon @click="changePrimaryColors('#8e8374')"
                              :class="[ 'default', { active: globalConf.appPrimaryColor === '#8e8374' } ]"
                              color="#8e8374" size="34">
                        <icon-ep-circle-check-filled/>
                      </n-icon>
                    </n-space>
                  </template>
                </n-thing>

                <!--字体缩放-->
                <n-thing content-class="thing-content">
                  <template #header>
                    <span class="thing-title">{{ $confI18n.fontSize }}</span>
                  </template>
                  <template #default>
                    <n-space vertical>
                      <n-slider v-on:update:value="changeZoom"
                                v-model:value="globalConf.appZoomFactor"
                                style="width: 80%"
                                :min="0.6"
                                :max="1.4"
                                :marks="{ 0.6: '60%', 0.8: '80%', 1.0: '100%', 1.2: '120%', 1.4: '140%' }"
                                :step="0.1"/>
                    </n-space>
                  </template>
                </n-thing>

              </n-card>

              <!--通用-->
              <n-card class="conf--aside__thing" :bordered="false" :title=" $confI18n.common " id="AnchorGeneral">

                <!--开机设置-->
                <n-thing content-class="thing-content">
                  <template #header>
                    <span class="thing-title">{{ $confI18n.powerSetting }}</span>
                  </template>
                  <template #default>
                    <n-space>
                      <n-checkbox size="large" :checked="globalConf.loginPowerOn" :label="$confI18n.powerSelfStart"
                                  @update:checked="changePowerSetting"/>
                    </n-space>
                  </template>
                </n-thing>

                <!--关闭应用-->
                <n-thing content-class="thing-content">
                  <template #header>
                    <span class="thing-title" v-text=" $confI18n.closeApp "></span>
                  </template>
                  <template #default>
                    <n-space vertical>
                      <n-radio
                          :checked=" globalConf.appCloseWindow === 'minimize' "
                          value="minimize"
                          name="window-close-setting"
                          @change="changeCloseWinSetting"
                      >
                        {{ $confI18n.minimum }}
                      </n-radio>
                      <n-radio
                          :checked=" globalConf.appCloseWindow === 'quit' "
                          value="quit"
                          name="window-close-setting"
                          @change="changeCloseWinSetting"
                      >
                        {{ $confI18n.closeExit }}
                      </n-radio>
                    </n-space>
                  </template>
                </n-thing>

                <!--国际化语言-->
                <n-thing content-class="thing-content">
                  <template #header>
                    <span class="thing-title">{{ $confI18n.selectLanguage }}</span>
                  </template>
                  <template #default>
                    <n-space>
                      <n-radio
                          :checked=" globalConf.appLanguageI18n === 'zh-CN' "
                          value="zh-CN"
                          name="app-language-setting"
                          @change="changeLanguageSetting"
                      >
                        {{ $confI18n.chinese }}
                      </n-radio>
                      <n-radio
                          :checked=" globalConf.appLanguageI18n === 'en-US' "
                          value="en-US"
                          name="app-language-setting"
                          @change="changeLanguageSetting"
                      >
                        {{ $confI18n.english }}
                      </n-radio>
                    </n-space>
                  </template>
                </n-thing>

                <!--软件更新-->
                <n-thing content-class="thing-content" v-if="!globalConf._systemUpdaterForce">
                  <template #header>
                    <span class="thing-title">{{ $confI18n.softwareUpdate }}</span>
                  </template>
                  <template #default>
                    <n-space vertical>
                      <n-radio
                          :checked=" globalConf.appAutoUpdates === 'autoupdate' "
                          value="autoupdate"
                          name="app-update-setting"
                          @change="changeUpdaterSetting"
                      >
                        {{ $confI18n.autoUpdates }}
                      </n-radio>
                      <n-radio
                          :checked=" globalConf.appAutoUpdates === 'sendnotify' "
                          value="sendnotify"
                          name="app-update-setting"
                          @change="changeUpdaterSetting"
                      >
                        {{ $confI18n.notifyMe }}
                      </n-radio>
                    </n-space>
                  </template>
                </n-thing>

                <!--下载设置-->
                <n-thing content-class="thing-content">
                  <template #header>
                    <div class="thing-title">
                      <span>{{ $confI18n.downloadSettings }}</span>
                      <n-button @click="changeDownloadPath" style="margin-left: 12px" secondary type="primary"
                                size="tiny">更改
                      </n-button>
                    </div>
                  </template>
                  <template #default>
                    <div>
                      <span>{{ $confI18n.storagePath }}</span>
                      <span>{{ globalConf.appDownloadsPath }}</span>
                    </div>
                  </template>
                </n-thing>

              </n-card>
              <!--关于-->
              <n-card class="conf--aside__thing" :bordered="false" :title="$confI18n.about" id="AnchorAbout">

                <!--版本信息-->
                <n-list style="background-color: inherit;">
                  <n-list-item style="padding-top: 0;padding-bottom: 24px;">
                    <n-thing>
                      <template #avatar>
                        <img src="@/assets/logo.png" width="86px" alt="Logo">
                      </template>
                      <template #header>
                        <h3 style="margin: 0;">{{ AppProductName }}</h3>
                      </template>
                      <template #description>
                        <n-space vertical style="min-width: 220px;">
                          <span style="color: var(--text-color-3);font-size: 13px;">{{
                              $confI18n.currentVersion
                            }}{{ AppProductVersion }}</span>
                          <n-space>
                            <n-button type="primary" :loading="fetchAvailableUpdateLoading" @click="checkForUpdate">
                              {{ $confI18n.checkForUpdates }}
                            </n-button>
                            <n-button @click="getChangelog">
                              {{ $confI18n.viewUpdateLog }}
                            </n-button>
                            <n-modal class="model__confirm-btn-center"
                                     style="margin:32px auto;"
                                     v-model:show="changeLogShow"
                                     preset="dialog"
                                     :title=" $confI18n.changeLog "
                                     positive-text="确定"
                            >
                              <Changelog :content="changeLogContent"/>
                            </n-modal>
                          </n-space>
                        </n-space>
                      </template>
                    </n-thing>
                  </n-list-item>

                  <!--友情链接-->
                  <n-list-item style="padding-top: 36px;">
                    <n-space vertical>
                      <n-thing>
                        <template #default>
                          <n-flex :size="4" align="center">
                            <n-icon>
                              <icon-ep-link/>
                            </n-icon>
                            <a style="color: var(--text-color-2)" href="https://www.kaka996.com/"
                               target="_blank">{{ $confI18n.userServiceAgreement }}</a>
                          </n-flex>
                        </template>
                      </n-thing>
                      <n-thing>
                        <template #default>
                          <n-flex :size="4" align="center">
                            <n-icon>
                              <icon-ep-link/>
                            </n-icon>
                            <a style="color: var(--text-color-2)" href="https://www.electronjs.org/"
                               target="_blank">{{ $confI18n.privacyPolicy }}</a>
                          </n-flex>
                        </template>
                      </n-thing>
                      <n-thing>
                        <template #default>
                          <n-flex :size="4" align="center">
                            <n-icon>
                              <icon-ep-link/>
                            </n-icon>
                            <a style="color: var(--text-color-2)" href="https://www.naiveui.com/zh-CN/" target="_blank">{{
                                $confI18n.contactUs
                              }}</a>
                          </n-flex>
                        </template>
                      </n-thing>
                      <n-thing>
                        <template #default>
                          <n-flex :size="4" align="center">
                            <n-icon>
                              <icon-ep-link/>
                            </n-icon>
                            <a style="color: var(--text-color-2)"
                               href="https://element-plus.org/zh-CN/component/icon.html#icon-collection"
                               target="_blank">{{ $confI18n.copyright }}</a>
                          </n-flex>
                        </template>
                      </n-thing>
                    </n-space>
                  </n-list-item>

                </n-list>

              </n-card>
            </n-scrollbar>
          </n-card>
        </div>
      </template>
    </n-card>
  </div>
</template>

<style scoped lang="less">
@main-max-height: calc(100vh - 60px);
@right-max-width: calc(100vw - 150px);

.conf {
  -webkit-user-select: none;
  height: 100%;
  box-shadow: var(--n-box-shadow);

  &--card {
    height: 100%;
  }

  :deep(&--card-header) {
    -webkit-app-region: drag;
    -webkit-user-select: none;
    border-bottom: 1px solid var(--n-border-color);
  }

  :deep(&--card-content) {
    padding: 0;
  }

  &--titlebar {
    &_text {
      -webkit-app-region: no-drag;
      width: fit-content;
      font-size: 16px;
      line-height: 16px;
    }
  }

  &--close {
    -webkit-app-region: no-drag;
    cursor: pointer;
    padding: 8px;
    border-radius: 6px;
    color: var(--text-color-2);

    &:hover {
      background-color: var(--error-background-color);
      color: var(--error-color-hover);
    }
  }

  &--aside {
    height: 100%;
    display: flex;

    &__tree {
      width: 150px;
      height: 100%;
      max-height: @main-max-height;
      -webkit-flex-shrink: 0;
      background-color: inherit;
      border-right: 1px solid var(--n-border-color);

      :deep(.n-anchor-link) {
        line-height: 2.5;
        margin-top: 8px;
        margin-bottom: 8px;
      }

      :deep(.n-anchor-link__title) {
        padding-left: 8px;
        padding-right: 0 !important;
      }

    }

    :deep(&__menu) {
      height: 100%;
      padding: 0 !important;
    }

    &__content {
      flex: 1;
      max-width: @right-max-width;
      height: 100%;
      max-height: @main-max-height;
      background-color: inherit;
    }

    :deep(&__container) {
      height: 100%;
      padding: 0 !important;
    }

    &__thing {
      background-color: inherit;
      border-bottom: 1px solid var(--divider-color);

      &:last-child {
        height: @main-max-height;
      }

      //公共块
      :deep(.thing-content) {
        margin-top: 0 !important;
        margin-bottom: 36px;
      }

      .thing-title {
        font-size: 15px;
      }

      //外观
      .bg-options {
        display: flex;
        align-items: center;

        .item {
          font-size: 70px;
          width: 1em;
          border: 4px solid transparent;
          border-radius: 8px;
          cursor: pointer;

          &.active {
            border-color: var(--primary-color);
          }

          &:not(:last-child) {
            margin-right: 24px;
          }
        }
      }

      .default {
        width: fit-content;
        background-color: currentColor;
        border-radius: 50%;
        cursor: pointer;
        border: 3px solid transparent;
        transition: .3s ease-in;

        &.active {
          background-color: #fff;
          border-color: var(--primary-color);
          transition: .3s ease-in;
        }
      }

      //通用

    }

  }
}

</style>